"""
请使用 pip 安装 DrissionPage：

pip install DrissionPage
"""

# 导入
from DrissionPage import ChromiumPage, ChromiumOptions
import pytesseract
from PIL import Image

import pytesseract

pytesseract.pytesseract.tesseract_cmd = r'C:\Users\guangliang.han\AppData\Local\Programs\Tesseract-OCR\tesseract.exe'

co = ChromiumOptions()

# 设置启动时最大化
co.set_argument('--start-maximized')

 
def myb():
    return '107001023', 'Moby@2024..'


def hgl():
    return 'guangliang.han', 'HGLnihao,c806r4'


def tqw():
    return '090970', 'Tqw@19971217'


def main(code):
    """
    主函数 主要进行点检任务
    :return:
    """

    user = hgl()

    if code == 0:
        user = hgl()
    elif code == 1:
        user = myb()
    elif code == 2:
        user = tqw()

    login_url = 'https://apaas.jinkosolar.com:7001/workbench-center/workbench'

    username, password = user

    # 创建对象
    page = ChromiumPage()

    # 访问网页
    page.get(login_url)

    page.wait.load_start()

    page('@class=login-sso').click()

    page.wait.load_start()

    page('#txt_username').input(username)
    page('#txt_password').input(password)

    page.wait.load_start()

    # 处理验证码
    max_attempts = 10  # 最大尝试次数
    attempt = 0

    while attempt < max_attempts:
        # 获取验证码图片元素
        captcha_element = page('#ver_code')
        # 保存验证码图片
        captcha_element.get_screenshot(path='captcha.png')
        # 使用OCR识别验证码
        captcha_image = Image.open('captcha.png')
        captcha_text = pytesseract.image_to_string(captcha_image, config='--psm 8')
        # 清理识别结果
        cleaned_captcha = ''.join(captcha_text.split())

        # 检查验证码长度
        if len(cleaned_captcha) == 4:
            page('#code_input').input(cleaned_captcha)
            break
        else:
            attempt += 1
            if attempt < max_attempts:
                print(f"验证码长度不正确 ({len(cleaned_captcha)} 位)，重新识别... (第{attempt}次)")
                page.wait(1)  # 等待1秒后重试
            else:
                print("验证码识别失败，已达最大重试次数")
                # 可以选择手动输入或退出程序
                manual_captcha = input("请输入验证码: ")
                page('#code_input').input(manual_captcha)

    page('#btn').click()

    page.wait.load_start()

    # page.get(spot_url)

    page.wait.load_start()

    page.ele('@class=ant-btn ant-btn-primary list-action-add').click()

    page.wait.load_start()

    page.ele('@placeholder=请选择').click()

    page.wait.load_start()

    items = page.eles('@class=sheet__row')

    for item in items[:-1]:
        item.click()

    # page.ele('机房巡检表').click()
    # page.ele('网络巡检表').click()
    # page.ele('系统管理组底层硬件巡检表').click()

    page.ele('确 定').click()

    page.wait.load_start()

    page.ele('提 交').click()

    page.wait.load_start()

    page.quit()


if __name__ == '__main__':
    main(0)
